package com.iqismart.shorturl.service.impl;

import com.iqismart.shorturl.config.UidHolder;
import com.iqismart.shorturl.model.EntityLog;
import com.iqismart.shorturl.model.EntityUrl;
import com.iqismart.shorturl.repository.LogRepository;
import com.iqismart.shorturl.repository.UrlRepository;
import com.iqismart.shorturl.service.LogService;
import com.iqismart.shorturl.vo.LogRequest;
import com.iqismart.shorturl.vo.LogResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Locale;

/**
 * @Description
 * @Auther sty
 * @createTime 2019-10-15 15:19
 */
@Service
@Slf4j
public class LogServiceImpl implements LogService {

    @Autowired
    private LogRepository logRepository;

    @Autowired
    private UrlRepository urlRepository;

    @Override
    public LogResponse add(LogRequest request) {
        try {
            EntityLog entityLog = new EntityLog();
            entityLog.setUrlId(request.getUrlId());
            entityLog.setIp(request.getIp());
            entityLog.setUserAgent(request.getUserAgent());
            entityLog.setReferer(request.getReferer());

            String ipCity = "";
            //TODO 查询IP城市
            entityLog.setIpCity(ipCity);

            entityLog.setUid(UidHolder.getUid());
            entityLog = logRepository.save(entityLog);
            LogResponse response = new LogResponse();
            BeanUtils.copyProperties(entityLog,response);

            return response;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    @Override
    public Long getTodayAdd() {
        Long count = urlRepository.count((Specification<EntityUrl>)(root, cq, cb)-> cb.and(cb.greaterThanOrEqualTo(root.get("createTime"),getTodayTime())));
        return count;
    }

    @Override
    public Long getTodayGet() {
        Long count = logRepository.count((Specification<EntityLog>)(root,cq,cb)-> cb.and(cb.greaterThanOrEqualTo(root.get("createTime"),getTodayTime())));
        return count;
    }

    @Override
    public Long getTotalAdd() {
        return urlRepository.count();
    }

    @Override
    public Long getTotalGet() {
        return logRepository.count();
    }

    @Override
    public Long getIP(Long urlId) {
        return logRepository.countIP(urlId);
    }

    @Override
    public Long getPV(Long urlId) {
        return logRepository.countPV(urlId);
    }

    private long getTodayTime() {
        Calendar cal = Calendar.getInstance(Locale.CHINA);
        cal.set(Calendar.HOUR_OF_DAY,0);
        cal.set(Calendar.MINUTE,0);
        cal.set(Calendar.SECOND,0);
        cal.set(Calendar.MILLISECOND,0);
        return cal.getTimeInMillis();
    }
}
